package com.leetcode.math;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipInputStream;

public class InsertInterval {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> resList = new ArrayList<>();
        int left = newInterval[0];
        int right = newInterval[1];
        boolean isPlaced = false;
        for (int[] interval : intervals) {
            if (interval[0] > right) {
                if (!isPlaced) {
                    resList.add(new int[]{left, right});
                    isPlaced = true;
                }
                resList.add(interval);
            } else if (left > interval[1]) {
                resList.add(interval);
            } else {
                left = Math.min(interval[0], left);
                right = Math.max(interval[1], right);
            }
        }
        if (!isPlaced) {
            resList.add(new int[]{left, right});
        }
        int[][] resArr = new int[resList.size()][2];
        for (int i = 0; i < resList.size(); i++) {
           resArr[i] = resList.get(i);
        }
        return resArr;
    }
}
